<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" fullscreen>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm">
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6" v-if="mode != 'add'">
                    <el-form-item label="入库类型" prop="input_type">
                        <el-select v-model="form.input_type" placeholder="请选择" disabled>
                            <el-option label="采购单入库" :value="1"></el-option>
                            <el-option label="染色单入库" :value="2"></el-option>
                            <el-option label="加工单入库" :value="3"></el-option>
                            <el-option label="其他入库" :value="4"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="染色订单" prop="dye_id">
                        <el-input v-model="info.purchase_dye_code" placeholder="染色订单" readonly></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="仓库" prop="ware_id">
						<el-select v-model="form.ware_id" placeholder="请选择" filterable clearable>
							<el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="入库日期" prop="ware_date">
						<el-date-picker v-model="form.ware_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6" v-if="mode == 'add'">
                    <el-form-item label="入库类型" prop="input_type">
						<el-select v-model="form.input_type" placeholder="请选择" disabled>
							<el-option label="采购单入库" :value="1"></el-option>
							<el-option label="染色单入库" :value="2"></el-option>
							<el-option label="加工单入库" :value="3"></el-option>
							<el-option label="其他入库" :value="4"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6" v-if="mode != 'add'">
                    <el-form-item label="入库单号" prop="purchase_ware_code">
						<el-input v-model="form.purchase_ware_code" placeholder="入库单号" readonly></el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
					<el-form-item label="染色厂" prop="apply_id">
						<el-input v-model="info.apply_name" placeholder="染色厂" readonly></el-input>
					</el-form-item>
				</el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="品名" prop="goods_name">
						<el-input v-model="form.goods_name" placeholder="品名" readonly></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="订单类型" prop="plan_type_text">
						<el-input v-model="info.plan_type_text" placeholder="订单类型" readonly></el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="联系人" prop="linkman">
						<el-input v-model="info.linkman" placeholder="联系人" readonly></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="联系方式" prop="mobile">
						<el-input v-model="info.mobile" placeholder="联系方式" readonly></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="克重" prop="weight">
						<el-input v-model="form.weight" placeholder="克重" readonly>
                            <template #append>克/米</template>
                        </el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="单价" prop="price">
						<el-input v-model="form.price" placeholder="单价" readonly>
                            <template #append>元/米</template>
                        </el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :span="12">
                    <el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" clearable></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="采购数量" prop="total_num">
						<el-input v-model="info.total_num" placeholder="采购数量" readonly>
                            <template #append>匹</template>
                        </el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="已入库" prop="deliver_num">
						<el-input v-model="info.deliver_num" placeholder="已入库" readonly>
                            <template #append>匹</template>
                        </el-input>
					</el-form-item>
                </el-col>
            </el-row>

            <!-- 样本 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false">样本选择</el-link>
                <el-checkbox v-model="select_all" size="large" label="全选" @change="changeAll(select_all)" v-if="sampleList.length > 0" />
                <el-checkbox v-for="(item,index) in sampleList" :key="index" v-model="item.show" size="large" :label="item.name" @change="sampleChange(item)" />
            </el-form-item>
            
            <!-- 花型 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkFlower">花型选择</el-link>
                <el-tag v-for="(item,index) in flowerList" :key="index" :closable="mode != 'show'" type="info" style="margin-right: 20px" @close="delTag(index)">
                    {{ item.flower }}
                </el-tag>
            </el-form-item>

            <sc-form-table class="formtable" ref="table" v-model="order_detail" hideAdd hideDelete placeholder="暂无数据" show-summary :summary-method="handleSummary" :defaultCustom="true" :cellStyle="cellStyle" showIndex>
                <el-table-column prop="index" align="center" width="50"></el-table-column>
                <el-table-column label="花型" align="center" prop="flower">
                    <template #default="scope">
                        {{scope.row.flower}}
                    </template>
                </el-table-column>
                <el-table-column label="" align="center" prop="" width="150">
                    <template #default="scope">
                        {{scope.row.name}}
                    </template>
                </el-table-column>
                <el-table-column v-for="(item,index) in table_list" :key="index" :label="item.name.name" :prop="item.prop" align="center" class-name="input_input">
                    <template #header>
                        <div style="display: flex;align-items: center;justify-content: center;">
                            <el-popover placement="top" :width="200" trigger="click" v-model="popover">
                                <template #reference>
                                    <div @click="getFocus(item.prop)">{{item.name.name}}</div>
                                </template>
                                <div style="display: flex;align-items: center;">
                                    <el-input v-model="all_set_number" type="number" :ref="item.prop + '_color'" @mousewheel.prevent @input="color_input(item,$event)"></el-input>
                                </div>
                            </el-popover>
                        </div>
                    </template>
                    <template #default="scope">
                        <div v-if="scope.row.name == '入库数据'">
                            <el-input v-model="scope.row[item.prop]" type="number" @mousewheel.prevent placeholder="" @focus="common.inputFocus($event)" @input="totalComputed(scope.row)" class="inputDeep"></el-input>
                        </div>
                        <div v-else>
                            {{scope.row.ware_obj[item.prop]}}/{{scope.row.total_obj[item.prop]}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="合计" align="center" prop="total_number" width="150">
                    <template #default="scope">
                        <div v-if="scope.row.name == '入库数据'">
                            {{scope.row.total_number}}
                        </div>
                        <div v-else>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="单价(元/米)" align="center" width="150">
                    <template #default="scope">
                        <div v-if="scope.row.name == '订单数据'">
                            {{form.price}}
                        </div>
                        <div v-else>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="克重(克/米)" align="center" width="150">
                    <template #default="scope">
                        <div v-if="scope.row.name == '订单数据'">
                            {{form.weight}}
                        </div>
                        <div v-else>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="备注" align="center">
                    <template #default="scope">
                        <div v-if="scope.row.name == '入库数据'">
                            <el-input v-model="scope.row.remark" @mousewheel.prevent placeholder="备注" clearable></el-input>
                        </div>
                        <div v-else>
                        </div>
                    </template>
                </el-table-column>
            </sc-form-table>
        </el-form>
        <!-- <template #footer>
            <el-button @click="visible=false">取 消</el-button>
            <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit(0)">保 存</el-button>
        </template> -->
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
		</el-footer>
        <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsBack" @closed="dialog.goods = false" :query="{is_show: 1}"></select-goods>
        <select-sample v-if="dialog.sample" ref="sampleDialog" @success="sampleBack" @closed="dialog.sample = false" :query="{apply_id: form.apply_id,goods_id: form.goods_id,type: 1}"></select-sample>
        <select-flower v-if="dialog.flower" ref="flowerDialog" @success="flowerBack" @closed="dialog.flower = false"></select-flower>
    </el-dialog>
</template>

<script>

import selectGoods from '@/views/basic/goods/selectGoods.vue';
import SelectSample from '../selectSample.vue';
import SelectFlower from '@/views/business/purchase/arrival/selectFlower.vue';
export default {
    emits: ['success', 'closed'],
    components: { selectGoods, SelectSample, SelectFlower, },
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增染色入库',
                copy: '新增染色入库',
                edit: '编辑染色入库',
                show: '查看染色入库',
            },
            visible: false,
            isSaveing: false,
            form: {
                id: "",
                dye_id: "",
                purchase_ware_code: "",
                ware_id: "",
                ware_date: this.moment().format('YYYY-MM-DD'),
                input_type: 2,
                apply_id: "",
                goods_id: "",
                goods_name: "",
                price: "",
                weight: "",
                total_num: "",
                remark: "",
                
                select_colors: "",
                select_flower_param: [],
                select_sample_param: "",
                order_detail: [],
            },
            info: {
                purchase_dye_code: "",
                apply_name: "",
                plan_type_text: "",
                linkman: "",
                mobile: "",
                total_num: "",
                deliver_num: "",
            },
            rules: {
                ware_id: [ {required: true, message: '请选择仓库'} ],
                ware_date: [ {required: true, message: '请选择入库日期'} ],
            },
            dialog: {
                goods: false,
                sample: false,
                flower: false,
            },
            wareList: [],
            templateList: [],
            select_all: false,
            sampleList: [],
            table_list: [],
            flowerList: [],
            select_flower_param: [],
            order_detail: [],
            edit_order_detail: [],
            all_set_number: "",
        }
    },
    mounted() {
		this.getWare();
		this.getTemplate();
    },
    created() {
        // this.color_input = this.common.debounce(this.color_input, 1000);
	},
    methods: {
        cellStyle(row){
            let cellStyle = '';
            if(row.column.label != '花型' && row.column.label != '备注' && row.column.label != '合计' && row.column.label != '单价(元/米)' && row.column.label != '克重(克/米)' && row.column.fixed != 'left' && row.row.name != '订单数据'){
                cellStyle = {backgroundColor:'#FFF'}
            }else {
                cellStyle = {backgroundColor:'#f4f4f5'}
            }
            return cellStyle
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit() {
            let flower = []
            this.flowerList.map(item=>{
                flower.push({
                    flower: item.flower,
                    flower_image: item.flower_image,
                })
            })
            this.form.select_flower_param = flower
            let sample = []
            this.sampleList.map(item=>{
                if(item.show){
                    sample.push(item.name)
                }
            })
            this.form.select_colors = sample.join(',')
            let array = []
            let count = 0
            this.order_detail.map(item=>{
                if(item.name == '入库数据'){
                    
                    if(item.total_number){
                        count = Number(item.total_number) + count
                    }
                    array.push(item)
                }
            })
            this.form.total_num = count
            this.form.order_detail = array
            console.log('this.form :>> ', this.form);
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    var res = [];
                    if (this.form.id) {
                        res = await this.$API.business.purchase.house.edit.post(this.form);
                    } else {
                        res = await this.$API.business.purchase.house.add.post(this.form);
                    }
                    this.isSaveing = false;
                    if (res.code == 1) {
                        this.visible = false;
                        this.$emit('success', this.form, this.mode)
                        this.$message.success("操作成功")
                    } else {
                        this.$alert(res.message, "提示", {type: 'error'})
                    }
                }
            })
        },
        //表单注入数据
        async setData(data,val) {
            if(!val){
                this.form.id = data.id
                this.form.purchase_ware_code = data.purchase_ware_code
            }
            var res = await this.$API.business.purchase.house.detail.get({id: data.id});
            this.form.dye_id = res.data.dye_id
            this.form.ware_id = Number(res.data.ware_id)
            this.form.apply_id = res.data.apply_id
            this.info.apply_name = res.data.dyeFactory?.apply_name
            this.info.linkman = res.data.dyeFactory?.linkman
            this.info.mobile = res.data.dyeFactory?.mobile
            this.form.goods_id = res.data.goods_id
            this.form.goods_name = res.data.goods_Name
            this.info.plan_type_text = res.data.plan_type == 1 ? '白坯' : res.data.plan_type == 2 ? '半成品' : '成品'
            this.info.purchase_dye_code = res.data.dye?.purchase_dye_code
            this.info.total_num = res.data.dye?.total_num
            this.info.deliver_num = res.data.dye?.deliver_num
            this.form.remark = res.data.remark
            this.form.total_num = res.data.total_num
            this.form.select_sample_param = res.data.select_sample_param
            this.form.select_colors = res.data.select_colors
            this.form.select_flower_param = res.data.select_flower_param
            this.form.price = res.data.price
            this.form.weight = res.data.weight
            this.form.input_type = res.data.input_type
            this.form.select_colors = res.data.select_colors
            let sample = []
            let color = res.data.select_colors_all.split(',')
            color.map(item=>{
                sample.push({
                    show: res.data.select_colors.includes(item),
                    name: item
                })
            })
            this.sampleList = sample
            this.flowerList = res.data.select_flower_param
            this.select_flower_param = res.data.select_flower_param_all
            let colorName = []
            res.data.order_detail[0].color_data.map(item=>{
                if(res.data.select_colors.includes(item.color_name)){
                    colorName.push({
                        name: {
                            name: item.color_name,
                            enter_number: 0,
                            total_number: 0,
                        },
                        number: item.number
                    })
                }
            })
            this.table_list = colorName
            this.edit_order_detail = res.data.order_detail_all
            let array = []
            res.data.order_detail.map((item,index)=>{
                res.data.select_flower_param.map(item2=>{
                    if(item.flower == item2.flower){
                        const dynamicFields = Object.fromEntries(
                            this.table_list.map(item1 => {
                                const colorItem = item.color_data.find(c => c.color_name === item1.name.name);
                                return [item1.name.name, colorItem?.number || 0];
                            })
                        );
                        array.push({
                            index: index + 1,
                            flower: item2.flower,
                            flower_image: item2.flower_image,
                            name: '订单数据',
                            ware_obj: {},
                            total_obj: {},
                        })
                        array.push({
                            index: index + 1,
                            flower: item2.flower,
                            flower_image: item2.flower_image,
                            name: '入库数据',
                            remark: item.remark,
                            total_number: item.total_count,
                            ...dynamicFields
                        })
                    }
                })
            })
            this.order_detail = array
            this.updateTableList()
        },
        // 添加获取数据
        async getData(data){
            this.form.dye_id = data.id
            var res = await this.$API.business.dye.order.detail.get({id: data.id});
            this.form.apply_id = res.data.apply_id
            this.form.goods_id = res.data.goods_id
            this.info.purchase_dye_code = res.data.purchase_dye_code
            this.info.apply_name = res.data.dyeFactory?.apply_name
            this.info.linkman = res.data.dyeFactory?.linkman
            this.info.mobile = res.data.dyeFactory?.mobile
            this.form.goods_name = res.data.goods_name
            this.info.plan_type_text = res.data.plan_type == 1 ? '白坯' : res.data.plan_type == 2 ? '半成品' : '成品'
            this.info.total_num = res.data.total_num
            this.info.deliver_num = res.data.deliver_num
            this.form.weight = res.data.weight
            this.form.price = res.data.price
            let sample = []
            let color = res.data.select_colors.split(',')
            color.map(item=>{
                sample.push({
                    name: item
                })
            })
            this.sampleList = sample
            this.select_flower_param = data.select_flower_param
            this.edit_order_detail = res.data.order_detail
        },
        // 仓库
		async getWare() {
			var res = await this.$API.basic.ware.all.get();
			this.wareList = res.data
		},
        // 模版列表
		async getTemplate() {
			var res = await this.$API.basic.print.all.get();
			this.templateList = res.data
		},
        templateChange(e){
            let template = this.templateList.find(item => item.id == e)
            this.form.content = template.content
        },
        checkSample(e){
            this.dialog.sample = true
            this.$nextTick(() => {
                this.$refs.sampleDialog.open('add').setData(e)
            })
        },
        sampleBack(data){
            console.log('样本 :>> ', data);
            // this.form.customer_pro_sample_id = data.id
            let array = []
            let color = data.colors.split(',')
            color.map(item=>{
                array.push({
                    show: false,
                    name: item
                })
            })
            this.sampleList = array
            this.select_all = false
            this.table_list = []
        },
        changeAll(e){
            this.sampleList.map(item=>{
                item.show = e
            })
            this.updateTableList();
        },
        sampleChange(e){
            if(e.show == false){
                this.select_all = false
            }
            // this.getDbData()
            this.updateTableList();
        },
        updateTableList() {
            this.table_list = this.sampleList.filter(item => item.show)
            .map(item => ({
                name: {
                    name: item.name,
                    enter_number: 0,
                    total_number: 0,
                },
                prop: item.name,
            }));
            this.order_detail = this.order_detail.map(row => {
                const newRow = { ...row };
                this.table_list.forEach(col => {
                    newRow[col.prop] = newRow[col.prop] || 0;
                    if(newRow.name == '订单数据'){
                        this.edit_order_detail.map(item1=>{
                            item1.color_data.map(item2=>{
                                if(item1.flower == row.flower){
                                    if(item2.color_name == col.prop){
                                        newRow.ware_obj[col.prop] = this.mode == 'add' ? item2.ware_number : item2.purchase_ware_number,
                                        newRow.total_obj[col.prop] = this.mode == 'add' ? Number(item2.number) * Number(item1.order_count) : Number(item2.purchase_number) * Number(item1.order_count)
                                    }
                                }
                            })
                        })
                    }
                });
                this.totalComputed(newRow)
                return newRow;
            });
        },
        checkFlower(){
            let data = []
            if(this.mode != 'add'){
                data = JSON.stringify(this.select_flower_param)
            }else {
                data = this.select_flower_param
            }
            this.dialog.flower = true
            this.$nextTick(() => {
                this.$refs.flowerDialog.open('add').setData(data)
            })
        },
        flowerBack(data){
            console.log('花型 :>> ', data);
            let array = []
            // let array_data = []
            data.map(item =>{
                let exist = this.common.isExist(item.flower_image, this.flowerList, 'flower_image')
                if (exist) {
                    return
                }
                array.push({
                    flower: item.flower,
                    flower_image: item.flower_image,
                })
            })
            this.flowerList = [...this.flowerList, ...array]
            this.getDbData()
        },
        getDbData(){ 
            let array_data = []
            this.flowerList.map((item,index)=>{
                let exist = this.common.isExist(item.flower_image, this.order_detail, 'flower_image')
                if (exist) {
                    return
                }
                array_data.push({
                    index: index + 1,
                    flower: item.flower,
                    flower_image: item.flower_image,
                    name: '订单数据',
                    ware_obj: {},
                    total_obj: {},
                })
                array_data.push({
                    index: index + 1,
                    flower: item.flower,
                    flower_image: item.flower_image,
                    name: '入库数据'
                })
            })
            this.order_detail = [...this.order_detail, ...array_data]
            this.updateTableList()
        },
        delTag(index){
            // this.$confirm(`确定删除吗？`, '提示', {
            //     type: 'warning'
            // }).then(() => {
            //     const startIndex = index * 2
            //     this.flowerList.splice(index, 1)
            //     this.order_detail.splice(startIndex, 2)
            // }).catch(() => {})
            const startIndex = index * 2
            this.flowerList.splice(index, 1)
            this.order_detail.splice(startIndex, 2)
        },
        totalComputed(row){
            let count = 0
            this.table_list.map(item=>{
                count = Number(row[item.prop]) + count
                row.total_number = count
            })
            // this.total()
        },
        total(){
            let count = 0
            this.order_detail.map(item=>{
                if(item.total_number){
                    count = Number(item.total_number) + count
                }
            })
            this.form.total_num = count
        },
        handleSummary({ columns, data }) {
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '';
                    return;
                }
                if (index === 1) {
                    sums[index] = '合计';
                    return;
                }
                if(data.some(item1 => item1[column.property])){
                    // const values = data.map(item1 => Number(item1[column.property]));
                    const values = []
                    data.map(item1=>{
                        if(item1.name == '入库数据'){
                            values.push(Number(item1[column.property]))
                        }
                    })
                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        return !isNaN(value) ? prev + value : prev;
                    }, 0);
                }else {
                    sums[index] = '';
                }
            });
            return sums;
        },
        objectSpanMethod(row){
            if (row.columnIndex === 1) {
                if (row.rowIndex % 2 === 0) {
                    return {
                        rowspan: 2,
                        colspan: 1,
                    }
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    }
                }
            }
        },
        // 批量设置数量
        color_input(color,e){
            this.order_detail.map(item=>{
                item[color.prop] = e
                this.totalComputed(item)
            })
            // this.all_set_number = ""
        },

        getFocus(item){
            this.all_set_number = ""
            let e = `${item}_color`
            setTimeout(()=>{ 
                this.$nextTick(()=>{
                    this.$refs[e][0].focus()
                })
            },100)
        },
    }
}
</script>

<style lang="scss" scoped>

:deep(.el-input input[type="number"]::-webkit-outer-spin-button),   
:deep(.el-input input[type="number"]::-webkit-inner-spin-button) {
   -webkit-appearance: none;
   margin: 0;   
}

:deep(.el-input input[type="number"]) {
   -moz-appearance: textfield;
}
.inputDeep {
    .el-input__inner {
        cursor: default !important;
        text-align: center;
    }
    :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
        height: 20px;
        background: transparent;
        cursor: default;
        .el-input__inner {
            cursor: default !important;
            text-align: center;
        }
    }
}
</style>
